package com.example.mediamoudle.pickvideo;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.baselibrary.base.BaseActivity;
import com.android.baselibrary.utils.ToastUtils;

import com.example.mediamoudle.R;
import com.example.mediamoudle.databinding.ActivityShortvideoVideoPickerBinding;
import com.example.mediamoudle.main.itemDecoration.DividerGridItemDecoration;
import com.example.mediamoudle.utlis.DefaultItemTouchHelper;
import com.example.mediamoudle.utlis.PermissionUtils;
import com.example.mediamoudle.utlis.Util;


import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class PickVideoActivity extends BaseActivity<ActivityShortvideoVideoPickerBinding> {
    public static final String THUMBNAIL_PATH = "FilePick";
    public static final String IS_NEED_CAMERA = "IsNeedCamera";
    public static final String IS_TAKEN_AUTO_SELECTED = "IsTakenAutoSelected";

    public static final int DEFAULT_MAX_NUMBER = 9;
    public static final int COLUMN_NUMBER = 3;
    private int mMaxNumber = 1;
    /**
     * 最多选择视频数
     **/
    private int mCurrentNumber = 0;
    private RecyclerView mRecyclerView;
    private RecyclerView recycleViewChoose;
    private PickVideoAdapter mAdapter;
    private PickSelectVideoAdapter mSelectAdapter;
    private boolean isNeedCamera;
    private boolean isTakenAutoSelected;
    private ArrayList<VideoFile> mSelectedList = new ArrayList<>();
    private List<Directory<VideoFile>> mAll;
    private ProgressBar mProgressBar;
    private DefaultItemTouchHelper selectVideoItemTouchHelper;
    private TextView tvNext;

    private TextView tv_count;
    private TextView tv_folder;
    private LinearLayout ll_folder;
    private RelativeLayout rl_done;
    private RelativeLayout tb_pick;
    private FrameLayout pop_video_loading_fl;
    private RelativeLayout rl_bottom;
    private TextView tv_duration;
    /**
     * 计算总时长
     **/
    private boolean isLoad = true;
    private LinearLayout ll_empty;
    private int requestCodeWrite = 200;

    // ImportVideoDialog importVideoDialog;

    private boolean checkPermission = true;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//状态栏半透明
        // requestWindowFeature(Window.FEATURE_NO_TITLE);
       /* getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);*/


        // loadData();
    }

    @SuppressLint("WrongViewCast")
    public void initView() {
        mSelectedList.clear();
        ll_empty = findViewById(R.id.ll_empty);
        tv_duration = findViewById(R.id.tv_duration);
        rl_bottom = findViewById(R.id.rl_bottom);
        tv_count = findViewById(R.id.tv_count);
        tv_count.setText(mCurrentNumber + "/" + mMaxNumber);
        mRecyclerView = findViewById(R.id.rv_video_pick);
        GridLayoutManager layoutManager = new GridLayoutManager(this, COLUMN_NUMBER);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.addItemDecoration(new DividerGridItemDecoration(this));

        mAdapter = new PickVideoAdapter();
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnSelectStateListener((state, file) -> {
            if (state) {
                mSelectedList.add(file);
                mCurrentNumber++;
            } else {
                mSelectedList.remove(file);
                mCurrentNumber--;
            }
            //统计总时长
            countTotalDuration(mSelectedList);
            mSelectAdapter.setData(mSelectedList);

        });
       /* mAdapter.setOnPreviewListener((videoFile, mList, position) -> {
            Intent intent = new Intent(PickVideoActivity.this, PreviewVideoActivity.class);
            intent.putExtra(Constants.PICKER_VIDEO_INDEX,position);
            intent.putExtra(Constants.PICKER_VIDEO_LIST, new Gson().toJson(mList));
            intent.putExtra(Constants.PICKER_VIDEO_FLAG,"1");
            startActivityForResult(intent,Constants.RESULT_PICKER_PREVIEW_VIDEO);
        });*/

        recycleViewChoose = findViewById(R.id.recycler_view_choose);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recycleViewChoose.setLayoutManager(linearLayoutManager);
        mSelectAdapter = new PickSelectVideoAdapter(this);
        recycleViewChoose.setAdapter(mSelectAdapter);
        mSelectAdapter.setItemSelectListener(new PickSelectVideoAdapter.ItemSelectDeleteListener() {
            @Override
            public void deleteItemSelect(int pos) {
                mSelectedList.remove(pos);
                mCurrentNumber--;
                mSelectAdapter.notifyDataSetChanged();
                mAdapter.setCurrentNumber(mCurrentNumber);
                tv_count.setText(mCurrentNumber + "/" + mMaxNumber);
                //统计总时长
                countTotalDuration(mSelectedList);
                refreshData(mAll);
            }

            @Override
            public void VideoPreview(VideoFile videoFile, ArrayList<VideoFile> mList, int position) {
               /* logService().i("VideoPreview: videoFile:"+videoFile.getDuration()+",->position:"+position);
                Intent intent = new Intent(PickVideoActivity.this, PreviewVideoActivity.class);
                intent.putExtra(Constants.PICKER_VIDEO_INDEX,position);
                intent.putExtra(Constants.PICKER_VIDEO_LIST,new Gson().toJson(mList));
                intent.putExtra(Constants.PICKER_VIDEO_FLAG,"2");
                startActivityForResult(intent,Constants.RESULT_PICKER_PREVIEW_VIDEO);*/
            }
        });

        //  selectVideoItemTouchHelper = new ItemTouchHelper(new SelectVideoItemTouchHelper(mSelectedList, mSelectAdapter));
        // selectVideoItemTouchHelper.attachToRecyclerView(recycleViewChoose);
        selectVideoItemTouchHelper = new DefaultItemTouchHelper(new DefaultItemTouchHelper.DefaultItemTouchHelpCallback.OnItemTouchCallbackListener() {

            @Override
            public boolean onMove(int srcPosition, int targetPosition) {

                Collections.swap(mSelectedList, srcPosition, targetPosition);
                /**更新UI中的Item的位置，主要是给用户看到交互效果*/
                mSelectAdapter.notifyItemMoved(srcPosition, targetPosition);
                return true;
            }

            @Override
            public int getDragFlag(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                return ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            }

            @Override
            public void onItemDragStart(RecyclerView.ViewHolder viewHolder, int pos) {

            }

            @Override
            public void onItemDragEnd(RecyclerView.ViewHolder viewHolder, int pos) {

                mSelectAdapter.setData(mSelectedList);
                mSelectAdapter.notifyItemRangeChanged(0, mSelectAdapter.getItemCount());

            }
        });
        selectVideoItemTouchHelper.setDragEnable(true);
        selectVideoItemTouchHelper.attachToRecyclerView(recycleViewChoose);

        mProgressBar = findViewById(R.id.pb_video_pick);
        File folder = new File(getExternalCacheDir().getAbsolutePath() + File.separator + THUMBNAIL_PATH);
       /* if (!folder.exists()) {
            mProgressBar.setVisibility(View.VISIBLE);
        } else {
            mProgressBar.setVisibility(View.GONE);
        }*/
        tb_pick = findViewById(R.id.rl_top);
        pop_video_loading_fl = findViewById(R.id.pop_video_loading_fl);
        pop_video_loading_fl.setVisibility(View.GONE);
        ll_folder = findViewById(R.id.ll_folder);
       /* importVideoDialog = new ImportVideoDialog(this);
        importVideoDialog.setCancelListener(() -> {
               importVideoDialog.setProgress(0);    
        });*/
        tvNext = findViewById(R.id.tv_next);
        tvNext.setOnClickListener(v -> {
            if (mSelectedList != null && mSelectedList.size() > 0) {
                int duration = 0;
                for (int i = 0; i < mSelectedList.size(); i++) {
                    duration += (mSelectedList.get(i).getDuration());
                }

               /* if (duration< ShortVideoHelper.PICKER_SELECT_MIN_TIME) {
                    ToastUtils.showCenterToast(
                            PickVideoActivity.this,
                            R.string.shortvideo_picker_min_duration_limit
                    );
                    return;
                } else if (duration> ShortVideoHelper.PICKER_SELECT_MAX_TIME+999) {  //处理毫秒值超过限制秒数问题
                    *//**
                 * 只有超过最大限制的时候才会展示提示
                 *//*
                    ToastUtils.showCenterToast(
                            PickVideoActivity.this,
                            R.string.shortvideo_picker_max_duration_limit
                    );
                    return;
                }*/
                final int videoTime = duration;

               Intent intent =  new Intent();
                String path =    mSelectedList.get(0).getPath();
                Log.i("TAG", "initView: path:"+path);
                intent.putParcelableArrayListExtra("videoPath",mSelectedList);
                setResult(2000, intent);
                finish();


            }
        });


    }


    /**
     * * @Description 处理预览页返回的数据
     *
     * @Author yf
     * @Date 2022/11/16 0016 17:14
     */
    private void initList(ArrayList<VideoFile> listExtra, String flag) {
        if (flag.equals("1")) {
            /*for (int i = 0; i < listExtra.size(); i++) {
                MediaExtractor extractor = new MediaExtractor();
                try {
                    extractor.setDataSource(listExtra.get(i).getPath());
                    if (extractor.getTrackCount()<=1){
                        listExtra.remove(i);
                        extractor.release();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }*/
            mAdapter.setData(listExtra);
            for (int i = 0; i < listExtra.size(); i++) {
                if (listExtra.get(i).isSelected() && !mSelectedList.contains(listExtra.get(i))) {
                    mSelectedList.add(listExtra.get(i));
                } else if (!listExtra.get(i).isSelected() && mSelectedList.contains(listExtra.get(i))) {
                    mSelectedList.remove(listExtra.get(i));
                }
            }
        } else {
            mSelectedList.clear();

            for (int i1 = 0; i1 < listExtra.size(); i1++) {
                if (listExtra.get(i1).isSelected()) {
                    mSelectedList.add(listExtra.get(i1));
                    int index = mAdapter.getList().indexOf(listExtra.get(i1));
                    mAdapter.getList().get(index).setSelected(true);
                } else {
                    int index = mAdapter.getList().indexOf(listExtra.get(i1));
                    mAdapter.getList().get(index).setSelected(false);
                }
            }

            mAdapter.notifyDataSetChanged();

        }

        if (mSelectedList.size() > 0) {
            rl_bottom.setVisibility(View.VISIBLE);
            mSelectAdapter.setData(mSelectedList);
            tvNext.setText(String.format("选好了(%d)", mSelectedList.size()));
            //统计总时长
            countTotalDuration(mSelectedList);
            mAdapter.setCurrentNumber(mSelectedList.size());
        } else {
            rl_bottom.setVisibility(View.GONE);
        }
    }

    private void loadData() {
        FileFilter.getVideos(this, directories -> {
            mProgressBar.setVisibility(View.GONE);
            // Refresh folder list
           /* if (isNeedFolderList) {
                ArrayList<Directory> list = new ArrayList<>();
                Directory all = new Directory();
                all.setName("全部");
                list.add(all);
                list.addAll(directories);
                mFolderHelper.fillData(list);
            }*/
            if (isLoad) {
                if (directories.isEmpty()) {
                    ll_empty.setVisibility(View.VISIBLE);
                } else {
                    ll_empty.setVisibility(View.GONE);
                }
                mAll = directories;
                refreshData(directories);
            }


        });
    }


    private void refreshData(List<Directory<VideoFile>> directories) {

        boolean tryToFindTaken = isTakenAutoSelected;

        if (tryToFindTaken && !TextUtils.isEmpty(mAdapter.mVideoPath)) {
            File takenFile = new File(mAdapter.mVideoPath);
            tryToFindTaken = !mAdapter.isUpToMax() && takenFile.exists();
        }

        List<VideoFile> list = new ArrayList<>();
        for (Directory<VideoFile> directory : directories) {
            list.addAll(directory.getFiles());
            if (tryToFindTaken) {
                tryToFindTaken = findAndAddTaken(directory.getFiles());
            }
        }
        for (int i = 0; i < list.size(); i++) {
            VideoFile file = list.get(i);
            file.setSelected(false);

           /* try {

                MediaExtractor extractor = new MediaExtractor();

                extractor.setDataSource(file.getPath());
                Log.i("TAGasf", "refreshData: "+i+",-"+extractor.getTrackCount());
                if (extractor.getTrackCount()<=1){
                    Log.i("TAGasf", "refreshData2: "+i+",-"+Thread.currentThread().getName());
                    extractor.release();
                }else {
                    resultList.add(file);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }*/
        }

        for (VideoFile file : mSelectedList) {
            int index = list.indexOf(file);
            if (index != -1) {
                list.get(index).setSelected(true);
            } else {
                list.get(index).setSelected(false);
            }
        }

        mAdapter.setData(list);
    }

    private boolean findAndAddTaken(List<VideoFile> list) {
        for (VideoFile videoFile : list) {
            if (videoFile.getPath().equals(mAdapter.mVideoPath)) {
                mSelectedList.add(videoFile);
                mCurrentNumber++;
                mAdapter.setCurrentNumber(mCurrentNumber);
                tv_count.setText(mCurrentNumber + "/" + mMaxNumber);

                return true;
            }
        }
        return false;
    }

    /**
     * 计算总时长
     *
     * @param list
     */
    @SuppressLint("DefaultLocale")
    private void countTotalDuration(ArrayList<VideoFile> list) {
        int duration = 0;
        for (int i = 0; i < list.size(); i++) {
            duration += (list.get(i).getDuration());
        }
        tv_duration.setText("总时长：" + Util.getDurationString(duration));
        tvNext.setText(String.format("选好了(%d)", list.size()));
        if (list.size() > 0) {
            rl_bottom.setVisibility(View.VISIBLE);
        } else {
            rl_bottom.setVisibility(View.GONE);
        }
    }

    @Override
    public void onBackPressed() {

        super.onBackPressed();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (checkPermission) {
            checkPermission = false;
            checkWritePermissionForAlbum();
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        checkPermission = true;
    }

    /**
     * 相册需要读写权限
     */
    private void checkWritePermissionForAlbum() {
        // 授权
        if (ContextCompat.checkSelfPermission(
                this,
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED
        ) {
            loadData();

        } else {
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    requestCodeWrite
            );
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull @NotNull String[] permissions, @NonNull @NotNull int[] grantResults) {
        if (requestCode == requestCodeWrite) {
            if (PermissionUtils.requestPermissionSuccess(grantResults)) {
                loadData();
                return;
            }
            /**
             * 权限被拒绝
             */
            if (!PermissionUtils.shouldShowRequestPermissionRationale(this, permissions)) {

                ToastUtils.show(this, "权限被拒绝");
            }
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_shortvideo_video_picker;
    }

    @Override
    public void initListener() {

    }
}
